"""
技能数据库管理
提供技能库的管理和检索功能
"""

import json
import os
import logging
from typing import List, Dict, Any, Optional

logger = logging.getLogger(__name__)

class SkillDatabase:
    """技能数据库管理类"""
    
    def __init__(self, data_file: str = "knowledge_base/skills.json"):
        self.data_file = data_file
        self.skills = []
        os.makedirs(os.path.dirname(data_file), exist_ok=True)
        self._load_data()
        if not self.skills:
            self._init_default_skills()
    
    def _load_data(self):
        """加载技能数据"""
        try:
            if os.path.exists(self.data_file):
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    self.skills = json.load(f)
                logger.info(f"加载了 {len(self.skills)} 个技能")
            else:
                self.skills = []
        except Exception as e:
            logger.error(f"加载技能数据失败: {str(e)}")
            self.skills = []
    
    def _save_data(self):
        """保存技能数据"""
        try:
            with open(self.data_file, 'w', encoding='utf-8') as f:
                json.dump(self.skills, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"保存技能数据失败: {str(e)}")
            raise
    
    def _init_default_skills(self):
        """初始化默认技能数据"""
        default_skills = [
            {
                "id": "skill_001",
                "name": "Python",
                "category": "编程语言",
                "description": "Python是一种高级编程语言，广泛应用于数据分析、机器学习、Web开发等领域。",
                "level": "高级",
                "tags": ["编程语言", "数据分析", "机器学习", "Web开发"]
            },
            {
                "id": "skill_002",
                "name": "JavaScript",
                "category": "编程语言",
                "description": "JavaScript是一种脚本语言，主要用于Web前端开发，也可用于后端开发。",
                "level": "高级",
                "tags": ["编程语言", "前端开发", "Web开发", "Node.js"]
            },
            {
                "id": "skill_003",
                "name": "Vue.js",
                "category": "前端框架",
                "description": "Vue.js是一个渐进式JavaScript框架，用于构建用户界面。",
                "level": "中级",
                "tags": ["前端框架", "JavaScript", "Vue", "前端开发"]
            },
            {
                "id": "skill_004",
                "name": "React",
                "category": "前端框架",
                "description": "React是一个用于构建用户界面的JavaScript库，由Facebook开发。",
                "level": "中级",
                "tags": ["前端框架", "JavaScript", "React", "前端开发"]
            },
            {
                "id": "skill_005",
                "name": "MySQL",
                "category": "数据库",
                "description": "MySQL是一个关系型数据库管理系统，广泛应用于Web应用开发。",
                "level": "中级",
                "tags": ["数据库", "SQL", "关系型数据库", "后端开发"]
            },
            {
                "id": "skill_006",
                "name": "机器学习",
                "category": "人工智能",
                "description": "机器学习是人工智能的一个分支，通过算法让计算机从数据中学习。",
                "level": "高级",
                "tags": ["人工智能", "机器学习", "算法", "数据分析"]
            },
            {
                "id": "skill_007",
                "name": "Docker",
                "category": "运维工具",
                "description": "Docker是一个开源的容器化平台，用于应用程序的打包、分发和部署。",
                "level": "中级",
                "tags": ["容器化", "运维", "部署", "DevOps"]
            },
            {
                "id": "skill_008",
                "name": "Git",
                "category": "版本控制",
                "description": "Git是一个分布式版本控制系统，用于跟踪代码变更。",
                "level": "中级",
                "tags": ["版本控制", "Git", "代码管理", "协作开发"]
            }
        ]
        self.skills = default_skills
        self._save_data()
    
    def add_skill(self, skill_data: Dict[str, Any]) -> str:
        """添加新技能"""
        skill_id = f"skill_{len(self.skills) + 1:03d}"
        skill_data["id"] = skill_id
        self.skills.append(skill_data)
        self._save_data()
        return skill_id
    
    def get_all_skills(self) -> List[Dict[str, Any]]:
        """获取所有技能"""
        return self.skills
    
    def search_skills(self, query: str) -> List[Dict[str, Any]]:
        """搜索技能"""
        results = []
        query_lower = query.lower()
        for skill in self.skills:
            if (query_lower in skill["name"].lower() or
                query_lower in skill["description"].lower() or
                query_lower in skill["category"].lower()):
                results.append(skill)
        return results
    
    def get_skills_by_category(self, category: str) -> List[Dict[str, Any]]:
        """根据类别获取技能"""
        return [skill for skill in self.skills if skill.get("category") == category]
    
    def get_skill_categories(self) -> List[str]:
        """获取所有技能类别"""
        categories = set()
        for skill in self.skills:
            if "category" in skill:
                categories.add(skill["category"])
        return list(categories) 